using UnityEngine;
using System.Collections;

public class NetworkStart : MonoBehaviour {
	public string connectIP = "127.0.0.1";
	public int connectPort = 25001;
	// Use this for initialization
	void Start () {
	
	}
	
	void OnGUI(){
		if(GUI.Button(new Rect(800, 500, 200, 30), "Reset")){
			print("test");
		}
		if(Network.peerType == NetworkPeerType.Disconnected){
			GUI.Label(new Rect(10,10,200,30), "Connection status: Disconnected");
			connectIP = GUI.TextField(new Rect(10,60,150,30),connectIP);
			connectPort = int.Parse(GUI.TextField(new Rect(10,110,150,30),connectPort.ToString()));
			if(GUI.Button(new Rect(10,160,150,30),"Connect as client")){
				Network.Connect(connectIP,connectPort);
			}
			if(GUI.Button(new Rect(10,210,150,30),"Start Server")){
				Network.InitializeServer(4,connectPort,false);
				GameObject[] gos = FindObjectsOfType(typeof(GameObject)) as GameObject[];
				foreach(GameObject go in gos)
					go.SendMessage("OnNetworkLoadedLevel1",SendMessageOptions.DontRequireReceiver);
			}
		}
		else{
			if(Network.peerType == NetworkPeerType.Connecting)
				GUI.Label(new Rect(10,260,150,30),"Connection status: Connecting");
			else if(Network.peerType == NetworkPeerType.Client){
				GUI.Label(new Rect(10,260,150,30),"Connection status: Client");
				GUI.Label(new Rect(10,310,150,30),"Ping to server: " + Network.GetAveragePing(Network.connections[0]));
			}
			else if(Network.peerType == NetworkPeerType.Server){
				GUI.Label(new Rect(10,260,150,30),"Connection status: Server");
				GUI.Label(new Rect(10,310,150,30),"Connections: " + Network.connections.Length);
				for(int i = 0; i < Network.connections.Length; i++)
					GUI.Label(new Rect(10,360+50*i,150,30),"Ping to player " + i + ": " + Network.GetAveragePing(Network.connections[i]));
			}
		}
		if(GUI.Button(new Rect(10,500,150,30),"Disconnect"))
			Network.Disconnect(200);
	}
	void OnServerInitialized(){
	}
	void OnConnectedToServer(){
			GameObject[] gos = FindObjectsOfType(typeof(GameObject)) as GameObject[];
			foreach(GameObject go in gos)
				go.SendMessage("OnNetworkLoadedLevel",SendMessageOptions.DontRequireReceiver);
	}
	void OnDisconnectedFromServer(){
		if(this.enabled != false){
			Application.LoadLevel(0);
		}
	}
	
			
					
				
		
	
	// Update is called once per frame
	void Update () {
	
	}
}
